<template>
  <div class="page-container fullpage">
    <el-card>
  <h3>增加日程</h3>
      <el-form :model="form" ref="formRef" label-width="120px">
        <el-form-item label="用户名 *" prop="username">
          <el-input v-model="displayUsername" disabled />
        </el-form-item>

        <el-form-item label="任务名 *" prop="masname">
          <el-input v-model="form.masname" placeholder="例如：写报告" />
        </el-form-item>

        <el-form-item label="内容" prop="massion">
          <el-input type="textarea" v-model="form.massion" placeholder="任务详情" />
        </el-form-item>

        <el-form-item label="时间" prop="massiontime">
          <el-input v-model="form.massiontime" placeholder="格式：YYYY-MM-DD HH:mm:ss，例如 2025-10-18 05:33:47" />
          <div style="color:#909399;font-size:12px;margin-top:6px">提示：可手动输入完整时间，格式必须为 <code>YYYY-MM-DD HH:mm:ss</code></div>
        </el-form-item>

       

        <el-form-item>
          <el-button type="primary" @click="submit" :loading="loading">提交</el-button>
          <el-button style="margin-left:8px" @click="goBack">返回主界面</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../utils/api'
import { ElMessage } from 'element-plus'

const formRef = ref()
const loading = ref(false)

const form = ref({
  masname: '',
  massion: '',
  massiontime: null,
  createperson: null,
  updateperson: null
})

const username = localStorage.getItem('username') || ''
const displayUsername = username
const router = useRouter()

const goBack = () => { try { router.push('/dashboard') } catch (e) {} }

const submit = async () => {
  if (!form.value.masname) { ElMessage.error('请输入任务名'); return }
  if (!username) { ElMessage.error('当前未检测到登录用户名，请先登录'); return }
  loading.value = true
  try {
    
    try {
      const existResp: any = await api.get('/stumsg', { params: { username } })
      console.log('existing tasks for', username, existResp)
      const list = Array.isArray(existResp?.data) ? existResp.data : (Array.isArray(existResp) ? existResp : [])
      if (list && list.length) {
        const normalize = (s: any) => (s == null ? '' : String(s).trim().toLowerCase())
        const target = normalize(form.value.masname)
        const found = list.find((t: any) => normalize(t?.masname) === target)
        console.log('pre-check found same name?', !!found, 'target=', target)
        if (found) {
          ElMessage.error('创建失败：该用户下已存在同名任务（前端预检）')
        
          try { window.location.hash = '#/schedule/view' } catch (e) {}
          loading.value = false
          return
        }
      }
    } catch (e) {
      console.warn('预检 existing tasks 失败，继续尝试创建', e)
    }
    const payload: any = {
      username,
      masname: form.value.masname,
      massion: form.value.massion,
      
      createperson: 1,
      updateperson: 1
    }
    
    if (form.value.massiontime) {
      const raw = String(form.value.massiontime).trim()
      const datetimeRe = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/
      if (!datetimeRe.test(raw)) {
        ElMessage.error('时间格式错误，请使用 YYYY-MM-DD HH:mm:ss，例如：2025-10-18 05:33:47')
        loading.value = false
        return
      }
      payload.massiontime = raw
    }

    console.log('create stumsg payload ->', payload)

    const resp: any = await api.post('/stumsg', payload)
    console.log('create stumsg resp', resp)
    if (resp && resp.operationResult === 'SUCC') {
      ElMessage.success(resp.errorMsg || '创建成功')
      // 清空表单
      form.value.masname = ''
      form.value.massion = ''
      form.value.massiontime = null
      // 跳回主界面
      try { router.push('/dashboard') } catch (e) {}
    } else {
    
      ElMessage.error(resp?.errorMsg || '创建失败')
      if (resp?.errorCode === 'USER_QUERY_FAILED' && /同名|已存在/.test(resp?.errorMsg || '')) {
        try { window.location.hash = '#/schedule/view' } catch (e) {}
      }
    }
  } catch (err: any) {
    console.error(err)
  
    const serverMsg = err?.response?.data ?? err?.message ?? '请求失败'
    try {
      const text = typeof serverMsg === 'string' ? serverMsg : JSON.stringify(serverMsg)
      ElMessage.error(text)
    } catch (e) {
      ElMessage.error('请求失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.page-container { padding: 16px }
</style>
